#!/user/bin/env python
# -*- coding: utf-8 -*-
''' 
Author: Sjy
Description: 优化结果展示
'''

__all__= []
import json
import numpy as np
import copy
import csv
from PyQt5 import QtCore, QtWidgets, QtGui

import gui.controls.envs as envs
from ..actions import Actions


global SHOW_DLG
SHOW_DLG = None

class DlgShowOptimizationResult(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        global SHOW_DLG
        py3d = envs.GL.get_value('py3d')
        super().__init__(py3d)
        if SHOW_DLG!=None: return
        SHOW_DLG = self
        self.ui = _UI()
        self.ui.setupUi(self)
        # 重新启用信号
        self.finished.connect(self.closeDialog)
        self.resize(1200, 800)

    def init(self):
        data =  {}
        self.ui._init(copy.deepcopy(data))
    def on_save(self, data:dict={}):
        self.close()
        # 注意添加完了 需要更新tree 中对应位置的数据节点 用于显示

    def closeDialog(self):
        global SHOW_DLG
        SHOW_DLG = None
        self.deleteLater()

class _UI(QtWidgets.QWidget):
    sigOnSave = QtCore.pyqtSignal(dict)
    def __init__(self):
        super().__init__()
        self.parent = None
        self.__data = {}
    #自定义消息
    def setupUi(self, parent):
        # 纵向布局
        self.parent = parent
        self.parent.setWindowTitle("查看优化结果")


        self.__init_ui_layout()

        # layout = QtWidgets.QVBoxLayout(parent)
        # layout.setContentsMargins(10, 10, 10, 10)  # 设置整体边距
        # layout.setSpacing(5)  # 设置组件之间的间距

        # config = self.__get_ui_layout_config()
        # # ui_widget = envs.UILayout.CustomLayoutWidget(config, parent=parent)
        # # ui_widget.setMinimumSize(1200, 800)
        # # layout.addWidget(ui_widget)
        # layout.addWidget(config)

    def __init_ui_layout(self):
        layout = QtWidgets.QVBoxLayout(self.parent)
        layout.setContentsMargins(10, 10, 10, 10)  # 设置整体边距
        layout.setSpacing(5)  # 设置组件之间的间距

        self._ui_form = self.init_form()
        self._ui_table = self.init_table()
        
        btnCancel = QtWidgets.QPushButton("关闭")
        btnCancel.clicked.connect(self.parent.close)
        btnCancel.setMinimumWidth(80)
        btnCancel.setObjectName("DlgToolBtn")

        btnLayout = QtWidgets.QHBoxLayout()
        btnLayout.addWidget(btnCancel) 
        btnLayout.setAlignment(QtCore.Qt.AlignCenter)

        btnLayoutWidget = QtWidgets.QWidget()
        btnLayoutWidget.setLayout(btnLayout)

        # 添加组件到布局
        layout.addWidget(self._ui_form)
        layout.addWidget(self._ui_table, 1)  # 设置拉伸因子为1
        layout.addWidget(btnLayoutWidget)


        # return {
        #     "styles":{
        #         "gridColumn":1,
        #         "margin": [10, 10, 10, 10],  # 移除内部边距
        #         "spacing": 5,  # 减小组件间距
        #     },
        #     "grid": [ 
        #         [
        #             {
        #                 "widget": self._ui_form,
        #                 "styles":{
        #                     "colSpan": 1,
        #                 },
        #             },
        #         ],
        #         [
        #             {
        #                 "widget": self._ui_table,
        #                 "styles":{
        #                     "colSpan": 1,
        #                 },
        #             },
        #         ],
        #         [
        #             {
        #                 "widget": btnLayoutWidget,
        #                 "styles":{
        #                     "colSpan": 1,
        #                 },
        #             },
        #         ]
        #     ]
        # }

    def _init(self, data:dict={}) -> None:
        self.__data = data
        # 初始化表格数据
        self._init_table_data()

    def init_form(self):
        return envs.UIForm.UiCustomForm(self.__get_ui_form_config(), parent=self.parent)
    
    def init_table(self):
        """
        初始化优化结果表格
        """
        table = QtWidgets.QTableWidget()
        table.setObjectName("optimizationResultTable")
        
        # 设置表格属性
        table.setColumnCount(4)  # 移除序号列，使用表格自带的序号
        table.setHorizontalHeaderLabels([
            "搭接宽度", 
            "替换芯子的材料属性", 
            "上铺层修补层角度", 
            "极限承载力"
        ])
        
        # 设置表格属性
        table.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)  # 禁止编辑
        table.setSelectionBehavior(QtWidgets.QTableWidget.SelectRows)  # 整行选择
        table.setAlternatingRowColors(True)  # 交替行颜色
        
        # 显示垂直表头（序号）
        table.verticalHeader().setVisible(True)
        # 设置垂直表头样式
        table.verticalHeader().setDefaultAlignment(QtCore.Qt.AlignCenter)
        
        # 设置表头样式
        header = table.horizontalHeader()
        
        # 设置所有列自适应内容
        for i in range(table.columnCount()):
            header.setSectionResizeMode(i, QtWidgets.QHeaderView.Stretch)
        
        # 设置表格大小策略
        table.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        
        # 设置初始大小
        table.setMinimumHeight(400)  # 设置最小高度
        
        return table
    
    def _on_parent_resize(self, event, table):
        """
        处理父窗口大小变化事件
        """
        # 计算表格可用空间（考虑边距和间距）
        available_width = self.parent.width() - 20  # 减去左右边距
        available_height = self.parent.height() - 100  # 减去上下边距和其他组件高度
        
        # 设置表格大小
        table.setMinimumSize(available_width, available_height)
        table.setMaximumSize(available_width, available_height)
        
        # 调用原始的resizeEvent
        QtWidgets.QWidget.resizeEvent(self.parent, event)
    
    def _init_table_data(self, data:list=[]):
        """
        初始化表格数据
        """
        self._ui_table.setRowCount(len(data))
        
        for row, row_data in enumerate(data):
            for col, value in enumerate(row_data):
                item = QtWidgets.QTableWidgetItem(str(value))
                item.setTextAlignment(QtCore.Qt.AlignCenter)  # 居中对齐
                # col 要小于表格的列数
                if col < self._ui_table.columnCount():      
                    self._ui_table.setItem(row, col, item)
    
    def __get_ui_form_config(self) -> json:
        return {
            "size":[200,20],
            "items":[
                {
                    "type": "file",
                    "key":"csvFile",
                    "typeParams": {
                        "title": "优化结果文件",
                        "fileType": "CSV Files (*.csv)",
                        "onSelected": lambda file: self._on_select_file(file)
                    },
                    "styleParams":{
                        "margin": [0, 0, 0, 0],
                        "space": 10,
                        "labWidth": 100,
                        "minWidth": 200,
                    }
                },
            ]
        }
    
    def _on_select_file(self, file:str):
        """
        处理CSV文件选择
        Args:
            file: CSV文件路径
        """
        try:
            # 读取CSV文件
            with open(file, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                data = list(reader)  # 将迭代器转换为列表
                
                # 检查数据是否为空
                if not data:
                    print("警告：CSV文件为空")
                    return
                    
                # 更新表格数据
                self._init_table_data(data)
                
        except FileNotFoundError:
            print(f"错误：找不到文件 {file}")
        except UnicodeDecodeError:
            try:
                # 尝试使用其他编码
                with open(file, 'r', encoding='gbk') as f:
                    reader = csv.reader(f)
                    data = list(reader)
                    if not data:
                        print("警告：CSV文件为空")
                        return
                    self._init_table_data(data)
            except Exception as e:
                print(f"错误：无法读取文件 {file}，错误信息：{str(e)}")
        except Exception as e:
            print(f"错误：读取文件时发生错误 {str(e)}")
            # 打印测试数据
            data = [
                ["1", "10mm", "E=70GPa, ν=0.3", "45°", "1000N"],
                ["2", "15mm", "E=80GPa, ν=0.35", "60°", "1200N"],
                ["3", "20mm", "E=90GPa, ν=0.4", "90°", "1500N"],
            ]
            self._init_table_data(data)
    